/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.shuaijiang.net;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 *
 * @author atom
 */
public class NetInterfaceInfoUtil {
    
    
    /**
     * 
     * @return 
     */
    public static List<NetworkInterface> getNetworkInterfaces (){
       List<NetworkInterface> netInterfaces=new ArrayList<NetworkInterface>();
        try{
                Enumeration<NetworkInterface>networks =NetworkInterface.getNetworkInterfaces();
                 for (NetworkInterface netIf : Collections.list(networks)) {
                     netInterfaces.add(netIf);
                 }
        }catch(SocketException e){
            e.printStackTrace();
        }finally{
            return netInterfaces;
        }
    }
    
    public static List<NetworkInterface> getNetworkInterfaces(boolean isActive){
        List<NetworkInterface> netInterfaces=new ArrayList<NetworkInterface>();
        try{
                Enumeration<NetworkInterface>networks =NetworkInterface.getNetworkInterfaces();
                 for (NetworkInterface netIf : Collections.list(networks)) {
                    if(netIf.isUp()==isActive) netInterfaces.add(netIf);
                 }
        }catch(SocketException e){
            e.printStackTrace();
        }finally{
            return netInterfaces;
        }
    }
    
    
   
    
    /**
     *返回指定网卡的网络地址 
     * @param netinterface
     * @return 
     */
    public static List<InetAddress> getLocalIPAddress(String netinterface){
        List<InetAddress> LocalIpAddrs=new ArrayList<InetAddress>();
        try{
                NetworkInterface network=NetworkInterface.getByName(netinterface);
                for(InterfaceAddress addr:network.getInterfaceAddresses()){
                        LocalIpAddrs.add(addr.getAddress());
                }
        }catch(SocketException e){
            e.printStackTrace();
        }finally{
            return LocalIpAddrs;
        }
    }
    
    
    
    
   public static void main(String[]args){
       for(NetworkInterface network:NetInterfaceInfoUtil.getNetworkInterfaces(true)){
           System.out.println("networkInterface:"+network.getDisplayName());
           for(InetAddress add:getLocalIPAddress(network.getName())){
               System.out.println(""+add.getHostAddress());
           }
       }
       
   }
}
